<template>
  <div class="employees-box">
    <el-card>
      <div style="text-align: right">
        <!-- 导出 -->
        <el-button
          type="primary"
          size="mini"
          @click="exportExcel"
        >导出</el-button>
        <el-button
          v-btnControl="'import_into_btn'"
          type="primary"
          size="small"
          @click="$router.push('/employees/import')"
        >导入</el-button>
        <el-button
          icon="el-icon-plus"
          type="primary"
          size="small"
          @click="addEvent"
        >新增员工</el-button>
      </div>
    </el-card>
    <!-- 表格部分 -->
    <el-card style="margin-top: 15px">
      <el-table :data="list" border>
        <el-table-column label="序号" width="60px">
          <template v-slot="{ $index }">
            {{ (page.page - 1) * page.size + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="姓名" sortable prop="username" />
        <el-table-column label="用户头像" prop="staffPhoto">
          <template v-slot="{ row }">
            <div>
              <img
                v-errorimg
                class="avatar"
                :src="row.staffPhoto"
                alt=""
                @click="imgClick(row.staffPhoto)"
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="手机号" sortable prop="mobile" />
        <el-table-column label="工号" sortable prop="workNumber" />
        <el-table-column label="聘用形式" sortable prop="formOfEmployment">
          <template v-slot="{ row }">
            {{ row.formOfEmployment | getPx }}
          </template>
        </el-table-column>
        <el-table-column label="部门" sortable prop="departmentName" />
        <el-table-column label="入职时间" sortable prop="timeOfEntry">
          <template v-slot="{ row }">
            <div v-formatTime="row.timeOfEntry" />
          </template>
        </el-table-column>
        <!-- <el-table-column
          :formatter="formatterType"
          label="是否在职"
          sortable
          prop="enableState"
        /> -->
        <!-- 使用自定义指令 -->
        <!-- <el-table-column label="是否在职" sortable prop="enableState">
          <template v-slot="{ row }">
            <div v-formatType="row.enableState" />
          </template>
        </el-table-column> -->
        <!-- 不做任何处理再元素据上处理 -->
        <el-table-column label="是否在职" sortable prop="enableState2" />
        <!-- <el-table-column label="状态" sortable /> -->
        <el-table-column label="操作" width="300px">
          <template v-slot="{ row }">
            <el-button type="text" @click="look(row.id)">查看</el-button>
            <el-button type="text">转正</el-button>
            <el-button type="text">离职</el-button>
            <el-button type="text" @click="roleClick(row.id)">角色</el-button>
            <el-button type="text" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div style="text-align: right; padding: 15px 0px">
        <el-pagination
          :current-page="page.page"
          :page-sizes="[1, 5, 10]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹框 -->
    <Add ref="add" @getData="getData" />
    <!-- 生成二维码弹框 -->
    <el-dialog title="二维码弹框" :visible.sync="showQrcode">
      <div style="text-align: center">
        <canvas ref="canvas" />
      </div>
    </el-dialog>
    <!-- 角色弹框组件 -->
    <Role ref="role" />
  </div>
</template>

<script>
import Qrcode from 'qrcode'
import { sysUser, sysUserDel } from '@/api/employees'
import emloyeessData from '@/api/constant/employees'
import Add from './components/Add.vue'
import Role from './components/Role.vue'
// 导出表格方法
import { export_json_to_excel } from '@/vendor/Export2Excel'
export default {
  components: {
    Add,
    Role
  },
  // 过滤器
  filters: {
    // 聘用形式
    getPx(id) {
      const result = emloyeessData.hireType.find((item) => item.id === +id)
      return result ? result.value : '-'
    },
    // 状态
    getStatus(id) {
      const result = emloyeessData.workingState.find((item) => +item.id === +id)
      return result ? result.value : '-'
    }
  },
  data() {
    return {
      showQrcode: false,
      list: [{}],
      page: {
        page: 1,
        // 页容量即几条每页
        size: 10,
        total: 100
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 过滤
    formatterType(row, column, cellvalue, index) {
      const result = emloyeessData.workingState.find(
        (item) => +item.id === +cellvalue
      )
      return result ? result.value : '-'
    },
    // 点击触发改变当前页面的条数显示
    handleSizeChange(val) {
      this.page.size = val
      // jsCookie.set('emloyess-size', val)
      // 更新数据
      this.getData()
    },
    // 点击想要前往的页面直接跳到该页面
    handleCurrentChange(val) {
      // 把页当前的页数值存到page.page中
      this.page.page = val
      // 刷新页面
      this.getData()
    },
    // 获取员工详细信息
    async getData() {
      const res = await sysUser(this.page)
      // 转换数据
      res.data.rows.forEach((item) => {
        // item.enableState2 = item.enableState
        const result = emloyeessData.workingState.find(
          (i) => +i.id === item.enableState
        )
        item.enableState2 = result ? result.value : '-'
      })
      this.list = res.data.rows
      // 存储总条数
      this.page.total = res.data.total
    },
    addEvent() {
      this.$refs.add.isShow = true
    },
    // 删除员工
    del(id) {
      // 确定框
      this.$confirm('您确定删除该项吗？', '温馨提示')
        .then(async() => {
          const res = await sysUserDel(id)
          // 提示删除成功
          this.$message.success(res.message)
          // 判断该页是否只有条数据
          if (this.page.page > 1 && this.list.length <= 1) {
            this.page.page--
          }
          // 刷新父级
          this.getData()
        })
        .catch(() => {})
    },
    // 导出表格
    async exportExcel() {
      //  发起数据请求，获取到全部员工数据
      const res = await sysUser({
        page: 1,
        size: 9999
      })
      // 将数据进行转化成导出相应的格式，调用导出方法
      // 1、写好数据转换的规则
      const rules = {
        姓名: 'username',
        工号: 'workNummber',
        手机号: 'mobile',
        转正时间: 'correctionTime',
        部门: 'departmentName',
        是否在职: 'enableState',
        聘用形式: 'formOfEmployment'
      }
      // 处理数据
      const newArr = res.data.rows.map((item) => {
        const arr = []
        Object.values(rules).forEach((item2) => {
          arr.push(item[item2])
        })
        return arr
      })

      // 调用导出表格方法
      export_json_to_excel({
        header: Object.keys(rules), // 表头
        data: newArr, // 数据
        filename: '员工列表'
      })
    },
    // 查看员工详情界面
    look(id) {
      // 点击跳转到员工详情界面
      this.$router.push('/employees/userlook/' + id)
    },
    // 点击图片生成二维码
    imgClick(imageUrl) {
      if (imageUrl && imageUrl.trim()) {
        this.showQrcode = true
        // nextTick等他前面（它是一个异步，所有得同步都在面前）得东西渲染完成后执行
        this.$nextTick(() => {
          // 参数1：是放二维码得盒子，
          // 参数2:生成二维码图片地址
          // 参数3：对象：设置该二维码得宽高属性
          Qrcode.toCanvas(this.$refs.canvas, imageUrl, {
            width: 380,
            height: 380
          })
        })
      }
    },
    // 角色按钮
    async roleClick(id) {
      this.$refs.role.roleShow = true
      // 点击按钮把该角色的id值传过去
      this.$refs.role.getUserRole(id)
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-box {
  padding: 10px;
  .avatar {
    width: 30px;
    height: 30px;
    object-fit: contain;
  }
}
</style>
